package cn.user.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.user.Dto.ShopRegistrationDto;
import cn.user.Vo.ResponseVo;
import cn.user.Vo.ResultVo;
import cn.user.domin.ShopRegistration;
import cn.user.domin.ShopRegistrationExample;
import cn.user.mapper.ShopRegistrationMapper;
import cn.user.service.ShopRegistrationService;
import cn.util.TokenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.*;

import static com.alibaba.druid.util.Utils.read;


@Service
public class ShopRegistrationServiceImpl implements ShopRegistrationService {

    @Autowired
    private ShopRegistrationMapper mapper;


    @Override
    public int create(ShopRegistration shopRegistration) {
        return mapper.insert(shopRegistration);
    }

    @Override
    public int update(ShopRegistration shopRegistration) {
        return mapper.updateByPrimaryKeySelective(shopRegistration);
    }

    @Override
    public int delete(String recId) {
        return mapper.deleteByPrimaryKey(recId);
    }

    @Override
    public List<ShopRegistration> list(ShopRegistrationDto ShopRegistrationDto) {
        PageHelper.startPage(ShopRegistrationDto.getPageNum(), ShopRegistrationDto.getPageSize());
        ShopRegistrationExample shopRegistrationExample = new ShopRegistrationExample();
        ShopRegistrationExample.Criteria criteria = shopRegistrationExample.createCriteria();
        if(ObjectUtil.isNotEmpty(ShopRegistrationDto.getShopId())) {
            criteria.andShopIdEqualTo(ShopRegistrationDto.getShopId());
        }
        return mapper.selectByExample(shopRegistrationExample);
    }

    /**
     * 登录
     * @param shopRegistration 登录类
     * @return 返回类
     */
    @Override
    public ShopRegistration token(ShopRegistration shopRegistration) {
        ShopRegistrationExample shopRegistrationExample = new ShopRegistrationExample();
        ShopRegistrationExample.Criteria criteria = shopRegistrationExample.createCriteria();
        if(ObjectUtil.isNotEmpty(shopRegistration.getShopId())) {
            criteria.andShopIdEqualTo(shopRegistration.getShopId());
        }
        if(ObjectUtil.isNotEmpty(shopRegistration.getId())) {
            criteria.andIdEqualTo(shopRegistration.getId());
        }
        List<ShopRegistration> shopRegistrations = mapper.selectByExample(shopRegistrationExample);
        if(shopRegistrations.isEmpty()){
            ShopRegistration shopRegistration1 = new ShopRegistration();
            return shopRegistration1;
        }else{
            ShopRegistration shopRegistration1 = shopRegistrations.get(0);
            if(shopRegistration1.getShopId() != null ) {
                String token = TokenUtil.getToken(shopRegistration1.getId(), shopRegistration1.getShopId());
                shopRegistration1.setSpecificAddress(token);
                return shopRegistration1;
            }else{
                ShopRegistration shopRegistration2 = new ShopRegistration();
                return shopRegistration2;
            }
        }
    }

    @Override
    public ResultVo ProductInformation(String barCode) {
        ResponseVo responseVo1 = new ResponseVo();
        ResultVo result = responseVo1.getResult();
        String json ="";
        String host = "https://codequery.market.alicloudapi.com";// 【1】请求地址 支持http 和 https 及 WEBSOCKET
        String path = "/querybarcode";// 【2】后缀
        String appcode = "7199a12ff1114e5da6ca057fc3738ffe"; // 【3】开通服务后 买家中心-查看AppCode
        String code = "6920999705042"; // 【4】请求参数，详见文档描述
        String urlSend = host + path + "?code=" + code ; // 【5】拼接请求链接
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);// 格式Authorization:APPCODE
            // (中间是英文空格)
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                json = read(httpURLCon.getInputStream());
                System.out.println("正常请求计费(其他均不计费)");
                System.out.println("获取返回的json:");

            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    System.out.println("AppCode错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    System.out.println("请求的 Method、Path 或者环境错误");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    System.out.println("参数错误");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    System.out.println("服务未被授权（或URL和Path不正确）");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    System.out.println("套餐包次数用完 ");
                } else if (httpCode == 403 && error.equals("Api Market Subscription quota exhausted")) {
                    System.out.println("套餐包次数用完，请续购套餐");
                } else {
                    System.out.println("参数名错误 或 其他错误");
                    System.out.println(error);
                }
            }

        } catch (MalformedURLException e) {
            System.out.println("URL格式错误");
        } catch (UnknownHostException e) {
            System.out.println("URL地址错误");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ObjectMapper mapper = new ObjectMapper();
        try {
            ResponseVo responseVo = mapper.readValue(json, ResponseVo.class);
            result.setCode(responseVo.getResult().getCode());
            result.setGoodsName(responseVo.getResult().getGoodsName());
            result.setManuName(responseVo.getResult().getManuName());
            result.setGoodsType(responseVo.getResult().getGoodsType());
            result.setManuAddress(responseVo.getResult().getManuAddress());
            result.setSpec(responseVo.getResult().getSpec());
            result.setPrice(responseVo.getResult().getPrice());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }



    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }
}
